package routes

import (
	"errors"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/utils"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"path/filepath"
)

type InstallController struct {
	host    string
	ymlConf *comm.Conf
	scConf  *SourceConf
}

func (InstallController) GetPath() string {
	return "/api/install"
}
func (c *InstallController) Routes(g gin.IRoutes) {
	c.ymlConf = &comm.Conf{}
	g.Use(func(gcx *gin.Context) {
		if !comm.Installed {
			gcx.Next()
			return
		}
		gcx.String(500, "not found")
		gcx.Abort()
	})
	g.GET("/check", utils.GinReqParseJson(c.check))
	g.POST("/step-data", utils.GinReqParseJson(c.datas))
	g.POST("/step-host", utils.GinReqParseJson(c.hosts))
	g.POST("/step-source", utils.GinReqParseJson(c.source))
}

func (c *InstallController) saveConf() error {
	if c.ymlConf == nil || c.ymlConf.ServerConf == nil || c.ymlConf.ServerConf.Host == "" {
		return errors.New("server config err")
	}
	dir := filepath.Join(utils.HomePath(), ".giteeGo")
	bts, err := yaml.Marshal(c.ymlConf)
	if err != nil {
		return err
	}
	os.MkdirAll(dir, 0755)
	err = ioutil.WriteFile(filepath.Join(dir, "application.yaml"), bts, 0644)
	if err != nil {
		return err
	}
	return comm.InitConf()
}
